package com.lzh.dlykserver.manager;

import com.lzh.dlykserver.entity.TClue;
import com.lzh.dlykserver.entity.TCustomer;
import com.lzh.dlykserver.mapper.TClueMapper;
import com.lzh.dlykserver.mapper.TCustomerMapper;
import com.lzh.dlykserver.query.CustomerQuery;
import com.lzh.dlykserver.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class CustomerManager {

    @Resource
    private TCustomerMapper tCustomerMapper;

    @Resource
    private TClueMapper tClueMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean convertCustomer(CustomerQuery customerQuery) {

        //验证该线索是否已经转过客户
        TClue tClue = tClueMapper.selectByPrimaryKey(customerQuery.getClueId());
        if (tClue.getState() == -1) {
            throw new RuntimeException("该线索以及转过客户无法再次转换!!");
        }

        //向客户表插入一挑数据
        TCustomer tCustomer = new TCustomer();
        BeanUtils.copyProperties(customerQuery, tCustomer);

        int loginUserId = JWTUtils.parseUserFromJWT(customerQuery.getToken()).getId();
        tCustomer.setCreateBy(loginUserId);
        tCustomer.setCreateTime(new Date());

        int insert = tCustomerMapper.insertSelective(tCustomer);

        //把线索表的数据状态改为-1
        TClue clue = new TClue();
        clue.setId(customerQuery.getClueId());
        clue.setState(-1);
        int update = tClueMapper.updateByPrimaryKeySelective(clue);

        return insert >= 1 && update >= 1;
    }
}
